from src.db2sav.view import Ui_Form
from src.db2sav.userlogin import Ui_Frame
from src.db2sav.School_Nairer import school_naire, NaireJson
from src.db2sav.DataBase_Sav import DataBase_Sav
from src.db2sav.login import login, schoolLogin

from src.common.util import stopThreading
from setting import mysqlConfig
import os
import time
from threading import Thread
from PyQt5 import QtWidgets, QtGui
dbs = DataBase_Sav(mysqlConfig)
nj = NaireJson()

class setup(Ui_Frame, school_naire, Ui_Form):
    def __init__(self):
        import sys
        app = QtWidgets.QApplication(sys.argv)
        self.Frame = QtWidgets.QFrame()
        self.setupLoginUi(self.Frame)
        self.Frame.show()
        self.Form = QtWidgets.QWidget()
        self.setupUi(self.Form)

        self.configlogin()

        os._exit(app.exec_())

    def userLogin(self):
        """
        登录
        :return:
        """
        username = self.user_LE.text()
        password = self.password_LE.text()
        school = self.school_CB.currentText()
        self.user = username
        self.password_LE.setText("")
        data = {'username': username, 'password': password, 'superiorName': school}
        code, msg, self.token = login(data)

        if code == 1:
            QtWidgets.QMessageBox.information(self.Frame, "登录成功", msg)
            self.selectnaire()
            self.Frame.close()
            self.setupUi(self.Form)
            self.config()
            self.Form.show()
        else:
            QtWidgets.QMessageBox.critical(self.Frame, "登录失败", msg)

    def exitLogin(self):
        """
        退出登录
        :return:
        """
        self.Stu_cB.clear()
        self.naire_cB.clear()
        self.Form.close()
        self.setupLoginUi(self.Frame)
        self.configlogin()
        self.Frame.show()

    def configlogin(self):
        """
        登录数据初始化
        :return:
        """
        icon = QtGui.QIcon()
        palette = QtGui.QPalette()
        icon.addPixmap(QtGui.QPixmap("resourcese/img/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        palette.setBrush(QtGui.QPalette.Background, QtGui.QBrush(QtGui.QPixmap("resourcese/img/main_logo.jpg")))
        self.Frame.setPalette(palette)
        self.Frame.setWindowIcon(icon)
        self.Form.setPalette(palette)
        self.Form.setWindowIcon(icon)
        self.school_CB.addItems(schoolLogin())

    def config(self):
        """
        初始化数据
        :return:
        """
        self.showname_PB.setText("%s"%self.user)
        self.PC_PB.hide()
        self.exitlogin_PB.hide()
        self.setting_PB.hide()
        self.exit_PB.hide()
        List = []

        try:
            for n_id in self.n_idList:
                url = "https://api.cqtrust.cn/survey/index.php/dep/%d"% n_id
                response = eval(self.getHTMLText(url, self.token))
                if response['code'] != 1:
                    continue
                result = response['result']
                list = self.Schdata2List(n_id, result)
                List = List + list

            self.S_Dict, s_idList, school_Dict, self._school_Dict = self.List2Dict(List)
            s_nameList = ['All']
            for s_id in s_idList:
                result = self.S_Dict[s_id]
                s_name = result['s_name']
                s_nameList.append(s_name)
            self.Stu_cB.addItems(s_nameList)
            print(school_Dict)

        except:
            QtWidgets.QMessageBox.critical(self.Form, "拒绝访问", "学校&问卷信息解析失败")
            self.load_PB.hide()


    def download(self):
        """
        启动下载槽函数
        :return:
        """
        if self.naire_cB.currentText() == "请选择您要导出的问卷名称" or self.Stu_cB.currentText() == "请选择您要导出的学校":
            QtWidgets.QMessageBox.critical(self.Form, "无法导出问卷", "无法导出问卷，请检查学校或问卷是否正确")
        else:
            if self.load_PB.text() == "开始下载":
                self.thread = Thread(target=self.dataload)
                self.thread.start()
            else:
                self.load_PB.setText("开始下载")

    def stopDownload(self):
        stopThreading.stop_thread(self.thread)

    def dataload(self):
        self.load_PB.setText("下载中")
        self.load_PB.setEnabled(False)
        self.stopDownload_PB.setEnabled(True)
        """
        下载问卷
        :return:
        """
        log = ""
        all = 1
        success = 0
        defeat = 0
        path = self.path_LE.text()
        title = self.naire_cB.currentText()
        try:
            n_id = self._naireDict[title]

            if self.Stu_cB.currentText() == "All":
                url = "https://api.cqtrust.cn/survey/index.php/dep/%d" % n_id
                response = eval(self.getHTMLText(url, self.token))
                if response['code'] != 1:
                    pass
                result = response['result']

                all = len(result)
                log += f"一键导出模式\n预计导出{len(result)}所学校的{title}问卷\n开始时间{time.strftime('%Y-%m-%d %H:%M:%S')}\n"
                for sch in result:
                    table = "result%d" % sch['id']

                    try:
                        dbs.setupSav(path, n_id, sch['name'], table, self.naireDict)
                        success += 1
                        log += f"{time.strftime('%Y-%m-%d %H:%M:%S')} {sch['id']}_{sch['name']}-{title} 导出成功\n"
                    except Exception as e:
                        defeat += 1
                        log += f"{time.strftime('%Y-%m-%d %H:%M:%S')} {sch['id']}_{sch['name']}-{title} 导出失败\t失败原因：{e}\n"

                log += f"应导出：{all}\t成功：{success}\t失败：{defeat}\n"

            else:
                table = "result%d" % self.s_id
                log += f"按学校导出模式\n预计导出{self.s_id}_{self.s_name}的{title}问卷\n开始时间{time.strftime('%Y-%m-%d %H:%M:%S')}\n"
                try:
                    print(path, n_id, self.s_name, table, self.naireDict)
                    dbs.setupSav(path, n_id, self.s_name, table, self.naireDict)
                    success += 1
                    log += f"{time.strftime('%Y-%m-%d %H:%M:%S')} {self.s_id}_{self.s_name}-{title} 导出成功\n"
                except Exception as e:
                    defeat += 1
                    log += f"{time.strftime('%Y-%m-%d %H:%M:%S')} {self.s_id}_{self.s_name}-{title} 导出失败\t失败原因：{e}\n"

                log += f"应导出：{all}\t\t成功：{success}\t\t失败：{defeat}\n"

            # QtWidgets.QMessageBox.information(self.Form, "导出完成", f"导出成功{success}份问卷，导出失败{defeat}份问卷")
        except Exception as e:
            QtWidgets.QMessageBox.critical(self.Form, "导出失败", "导出失败")
            log += f"问卷导出失败\t失败原因：{e}\n"
            self.load_PB.setText("继续导出")
            self.load_PB.setEnabled(True)
        finally:
            filename = path+f"/{title}_log_{time.strftime('%Y-%m-%d-%H-%M-%S')}.txt"
            log += f"文件路径：{path}"
            with open(filename, "w+") as fp:
                fp.write(log)
            os.system(f"start {filename}")
            self.load_PB.setText("继续导出")
            self.load_PB.setEnabled(True)
            self.stopDownload_PB.setEnabled(False)


    def selectPath(self):
        """
        选择文件保存路径
        :return:
        """
        directory = QtWidgets.QFileDialog.getExistingDirectory(None, "选择文件夹", "/")
        self.path_LE.setText(directory)


    def selectnaire(self):
        """
        获取问卷信息（问卷id，问卷名称，及其对应关系）
        :return:
        """
        url = "https://api.cqtrust.cn/survey/index.php/naire/?order=desc&title="
        response = eval(nj.getHTMLText(url, self.token))
        result = response['result']
        self.n_idList, titleList, self.naireDict, self._naireDict = nj.naire2json(result)
        print(self.n_idList, titleList, self.naireDict, self._naireDict)

    def selectSchool(self):
        """
        选择要导出数据的学校
        :return:
        """
        self.naire_cB.clear()
        self.s_name = self.Stu_cB.currentText()
        if self.s_name == "All":
            titleList = []
            for n_id in self.n_idList:
                title = '%d_%s' % (n_id, self.naireDict[n_id])
                titleList.append(title)
            self.naire_cB.addItems(titleList)
        elif self.s_name == "请选择您要导出的学校":
            self.naire_cB.addItem("请选择您要导出的问卷名称")
        else:
            s_id = self._school_Dict[self.s_name]
            self.s_id = s_id
            n_idList = self.S_Dict[s_id]['n_id']
            titleList = []
            for n_id in n_idList:
                title = '%d_%s'% (n_id,self.naireDict[n_id])
                titleList.append(title)
            self.naire_cB.addItems(titleList)

    def showuser(self):
        """
        用户面板
        :return:
        """
        if self.showname_PB.text() == "隐藏":
            self.showname_PB.setText("%s"%self.user)
            self.PC_PB.hide()
            self.exitlogin_PB.hide()
        else:
            self.showname_PB.setText("隐藏")
            self.PC_PB.show()
            self.exitlogin_PB.show()

    def show_menu(self):
        """
        菜单面板
        :return:
        """
        if self.menu_PB.text() == "隐藏":
            self.menu_PB.setText("菜单")
            self.setting_PB.hide()
            self.exit_PB.hide()
        else:
            self.menu_PB.setText("隐藏")
            self.setting_PB.show()
            self.exit_PB.show()

    def EXIT(self):
        os._exit(0)


if __name__ == '__main__':
    ck = setup()

